from urllib.parse import quote_plus
from sqlalchemy.engine.base import Engine
from sqlalchemy import create_engine
from typing import Optional
from logging import getLogger
logger = getLogger(__name__)

__all__ = ['mysql_engine']

def mysql_engine(
    host: str,
    port: int,
    user: str,
    passwd: str,
    db: Optional[str] = None,
    pool_pre_ping:bool = False,
) -> Optional[Engine]:
    """
    生成 MySQL 数据库 SQLAlchemy 引擎。

    :param host: 数据库主机地址
    :param port: 数据库端口号
    :param user: 用户名
    :param passwd: 密码
    :param db: 数据库名（可选）
    :param pool_pre_ping: 是否提前创建连接
    :return: SQLAlchemy Engine 实例或 None（出错时）
    """
    try:
        user = quote_plus(user)
        passwd = quote_plus(passwd)
        engine = create_engine(f'mysql+pymysql://{user}:{passwd}@{host}:{port}/{db}',pool_pre_ping=pool_pre_ping)
        return engine
    except Exception as e:
        logger.error(f"An error occurred: {e}")
        return None